window.onload = function () {
  function bundleFile(filename) {
    var anchor = document.createElement('a');
    anchor.setAttribute('href', '{{bundlePath}}/' + filename);
    return anchor.href;
  }
  var files = [
    bundleFile('vendors.style.css'),
    bundleFile('commons.style.css'),
    bundleFile('{{appId}}.style.css'),

    bundleFile('vendors.bundle.js'),
    bundleFile('commons.bundle.js'),
    bundleFile('{{appId}}.bundle.js')
  ];

  (function next() {
    var file = files.shift();
    if (!file) return;

    var failure = function () {
      // make subsequent calls to failure() noop
      failure = function () {};

      var err = document.createElement('h1');
      err.style['color'] = 'white';
      err.style['font-family'] = 'monospace';
      err.style['text-align'] = 'center';
      err.style['background'] = '#F44336';
      err.style['padding'] = '25px';
      err.innerText = '{{i18n 'UI-WELCOME_ERROR'}}';

      document.body.innerHTML = err.outerHTML;
    }

    var type = /\.js(\?.+)?$/.test(file) ? 'script' : 'link';
    var dom = document.createElement(type);
    dom.setAttribute('async', '');
    dom.addEventListener('error', failure);

    if (type === 'script') {
      dom.setAttribute('src', file);
      dom.addEventListener('load', next);
      document.head.appendChild(dom);
    } else {
      dom.setAttribute('rel', 'stylesheet');
      dom.setAttribute('href', file);
      document.head.appendChild(dom);
      next();
    }
  }());
};
